package com.elitel.frame.base.controller;

import com.elitel.common.auth.AuthProperties;
import com.elitel.common.auth.controller.CommonLoginController;
import com.elitel.common.core.domain.SysUserInfo;
import com.elitel.frame.base.service.SysWhitelistService;
import com.elitel.frame.main.entity.SysWhitelist;
import com.elitel.frame.main.entity.vo.JsonResult;
import org.apache.commons.lang.StringUtils;
import org.jasig.cas.client.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@Controller
@RequestMapping({"/sys/user"})
public class LoginController implements CommonLoginController {
    Logger logger = LoggerFactory.getLogger(LoginController.class);
    public final static String SEQ = "_";
    @Resource
    private AuthProperties authProperties;

    @Resource
    private SysWhitelistService sysWhitelistService;

    /**
     * 获取用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("getLoginUser")
    @ResponseBody
    public JsonResult getLoginUser(HttpServletRequest request) {
        JsonResult jsonResult = new JsonResult();
        if (authProperties.getType()!=null&& AuthProperties.Type.NONE.equals(authProperties.getType())){
            jsonResult.setSuccess(true);
            return jsonResult;
        }
        try {
            HttpSession session = request.getSession(false);
            Assertion assertion = session != null ? (Assertion) session.getAttribute("_const_cas_assertion_") : null;
            if (assertion != null) {
                Object uname = assertion.getPrincipal().getAttributes().get(authProperties.getUsernameField());
                String username = uname == null ? null : String.valueOf(uname);
                if (StringUtils.isEmpty(username)) {
                    username = String.valueOf(assertion.getPrincipal().getName());
                }
                jsonResult.setSuccess(true);
                jsonResult.setData(username);
            } else {
                // 判断是不是系统登录
                Object sysWhitelistId = session != null ? (String) session.getAttribute(authProperties.getUsernameField()) : null;
                jsonResult.setSuccess(false);
                if (sysWhitelistId != null) {
                    String username = String.valueOf(sysWhitelistId).split(SEQ)[1];
                    if (StringUtils.isNotEmpty(username) && !"null".equals(username)) {
                        jsonResult.setSuccess(true);
                        jsonResult.setData(username);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("获取用户信息", e);
            jsonResult.setSuccess(false);
        }
        return jsonResult;
    }

    /**
     * 登录业务逻辑
     *
     * @param request
     * @param response
     * @param params   登录参数
     * @return 登录成功 返回true，否则返回false
     */
    @Override
    public SysUserInfo doLogin(HttpServletRequest request, HttpServletResponse response, SysUserInfo params) {
        try {
            SysWhitelist res = sysWhitelistService.login(params.getAccount(), params.getPassword());
            if (res == null) {
                logger.error("用户名或密码错误");
                return null;
            } else {
                HttpSession session = request.getSession();
                session.setAttribute(authProperties.getUsernameField(), res.getId() + SEQ + res.getUserName());
                SysUserInfo sysUserInfo = new SysUserInfo(res.getAccount(), res.getPassword());
                sysUserInfo.setVerifyFiledVal(res.getVerifyFiledVal());
                logger.error("当前用户验证字段对应的值是：{}", res.getVerifyFiledVal());
                return sysUserInfo;
            }
        } catch (Exception e) {
            logger.error("登录查询用户异常", e);
            throw new RuntimeException("登录查询用户异常");
        }
    }
}
